package com.li.configserve.config.i18n;

import com.li.toolkit.constant.LogConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 2021/12/16 21:29
 */
@Configuration
public class I18nConfig implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(I18nConfig.class);


    /**
     * 配置 MessageSource 其实这个可以不配置如果不配置请注意 message 多语言文件的位置
     *
     * @return
     */
    @Bean
    public ResourceBundleMessageSource messageSource() {
        Locale.setDefault(Locale.CHINESE);
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setBasenames("messages");
        source.setUseCodeAsDefaultMessage(true);
        source.setDefaultEncoding("UTF-8");
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "I18n配置完成");
        return source;
    }


    /**
     * 自定义国际化组件生效注册 LocaleResolver Bean
     *
     * @return
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocalResolver();
    }


}

class MyLocalResolver implements LocaleResolver {

    /**
     * 从请求中获取多语言参数，对当前域设置多语言环境
     *
     * @param request
     * @return
     */
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        final String key = "language";
        String language = request.getHeader(key);
        Map<String, String> map = new HashMap<>(16);
        map.put("en", Locale.ENGLISH.getLanguage());
        map.put("zh", Locale.CHINESE.getLanguage());
        return new Locale(map.getOrDefault(language, "en"));
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse httpServletResponse, Locale locale) {

    }
}